package com.wbao.dianniu.ui;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;

import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.conversation.IYWConversationService;
import com.alibaba.mobileim.conversation.IYWConversationUnreadChangeListener;
import com.alibaba.mobileim.login.IYWConnectionListener;
import com.alibaba.mobileim.login.YWLoginCode;
import com.lhh.apst.library.AdvancedPagerSlidingTabStrip2;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.data.SchemeEnum;
import com.wbao.dianniu.im.LoginSampleHelper;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.tabstrip.fragments.APSTSViewPager;
import com.wbao.dianniu.tabstrip.fragments.FirstFragment;
import com.wbao.dianniu.tabstrip.fragments.FourthFragment;
import com.wbao.dianniu.tabstrip.fragments.SecondFragment;
import com.wbao.dianniu.update.UpdateManager;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PermissionUtils;
import com.wbao.dianniu.utils.Utils;

import java.util.ArrayList;

public class MainActivity extends FragmentActivity implements OnPageChangeListener,UpdateManager.ICheckCompletedListener {
    public AdvancedPagerSlidingTabStrip2 mAPSTS;
    public APSTSViewPager mVP;

    private static final int VIEW_FIRST = 0;
    private static final int VIEW_SECOND = 1;
    private static final int VIEW_THIRD = 2;
    private static final int VIEW_FOURTH = 3;

    private final int VIEW_SIZE = 4;

    private FirstFragment fistfragment;
    private SecondFragment secondFragment;
    private Fragment mThirdFragment = null;
    private FourthFragment fourthFragment;

    private long firstTime;
    private int showPage;
    private Handler handler = null;
    private IYWConversationUnreadChangeListener mConversationUnreadChangeListener;
    private IYWConversationService mConversationService;
    private YWIMKit mIkit;
    private IYWConnectionListener mConnectionListener;
    private UpdateManager updateManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Utils.setTranslucentStatus(this, true);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.title_bg);// 通知栏所需颜色
        }
        setContentView(R.layout.activity_main_inc);
        initIM();
        Intent intent = getIntent();
        showPage = intent.getIntExtra(Const.INTENT_IS_MESSAGE, VIEW_FIRST);
        handler = new Handler();
        findViews();
        init();
        checkUpdate();
        schemeiInto();
    }

    private void schemeiInto() {
        Intent intent = getIntent();
        String type = intent.getStringExtra(Const.INTENT_SCHEME_TYPE);
        String id = intent.getStringExtra(Const.INTENT_SCHEME_ID);
        if (null != type && null != id) {
            Class cls = null;
            if (SchemeEnum.QUEST.equals(type)) {
                cls = QaDetailActivity.class;
            } else if (SchemeEnum.AM.equals(type)) {
                cls = AmDetailActivity.class;
            } else if (SchemeEnum.CARD.equals(type)) {
                cls = HeadInfoActivity.class;
            } else if (SchemeEnum.JOB.equals(type)) {
                cls = JobDetailsActivity.class;
            } else if (SchemeEnum.RECRUIT.equals(type)) {
                cls = RecruitDetailsActivity.class;
            } else if (SchemeEnum.ACT.equals(type)) {
                cls = ActivityDetail.class;
            } else if (SchemeEnum.KNOWLEDGE.equals(type)) {
                cls = KnowDetailActivity.class;
            }
            if (null == cls)
                return;
            Intent intoIntent = new Intent();
            intoIntent.putExtra(Const.INTENT_SCHEME_ID, id);
            intoIntent.setClass(MainActivity.this, cls);
            startActivity(intoIntent);
        }
    }

    /**
     * 检测更新
     */
    private void checkUpdate() {
        updateManager = new UpdateManager(this);
        updateManager.addCheckListener(this);
        updateManager.checkUpdate();
        /*long time = SharedPreferencesUtils.getUpdateTime(this);
        if (System.currentTimeMillis() - time > 1000 * 60 * 60 * 24) {
            SharedPreferencesUtils.setUpdateTime(System.currentTimeMillis());
            // 对比版本号更新
            int version = Utils.getVersionCode(this);
            int serviceCode = GlobalContext.versionCode;
            if (serviceCode > version) {
                UpdateManager update = new UpdateManager(this);
                update.checkUpdate();
            }
        }*/
    }

    private void findViews() {
        mAPSTS = (AdvancedPagerSlidingTabStrip2) findViewById(R.id.main_tabs);
        mVP = (APSTSViewPager) findViewById(R.id.main_apsts);
    }

    private void init() {
        mVP.setOffscreenPageLimit(VIEW_SIZE);
        mVP.setCurrentItem(showPage);
        FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager());
        mVP.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        mAPSTS.setViewPager(mVP);
        mAPSTS.setOnPageChangeListener(this);
        showUnreadCounts();
    }

    private void initIM() {
        mIkit = LoginSampleHelper.getInstance().getIMKit();
        if (null != mIkit) {
            mConversationService = mIkit.getConversationService();
            //添加IM连接状态监听
            addConnectionListener();
        }
        initConversationServiceAndListener();
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    @Override
    public void onPageSelected(int index) {
        if (VIEW_THIRD == index) {
        }

    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 800) {// 如果两次按键时间间隔大于800毫秒，则不退出
                Notification.toast(MainActivity.this, "再按一次退出程序");
                firstTime = secondTime;// 更新firstTime
                return true;
            } else {
//				LoginSampleHelper.getInstance().loginOut_Sample();
//				System.exit(0);// 否则退出程序 杀死进程
                this.finish();
            }
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void checkCompleted() {

    }

    @Override
    public void noCheck() {

    }

    @Override
    public void noPermission() {
        PermissionUtils.getInstance().showMsg(this,"更新失败，没有读取权限，\n请点击\"设置\"-\"权限管理\"-打开所有权限");
    }

    private class FragmentAdapter extends FragmentStatePagerAdapter implements AdvancedPagerSlidingTabStrip2.IconTabProvider {

        public FragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            if (position >= 0 && position < VIEW_SIZE) {
                switch (position) {
                    case VIEW_FIRST:
                        if (null == fistfragment)
                            fistfragment = FirstFragment.instance(MainActivity.this);
                        return fistfragment;
                    case VIEW_SECOND:
                        if (null == secondFragment)
                            secondFragment = SecondFragment.instance(MainActivity.this);
                        return secondFragment;

                    case VIEW_THIRD:
                        mThirdFragment = LoginSampleHelper.getInstance().getIMKit().getConversationFragment();
                        return mThirdFragment;
                    case VIEW_FOURTH:
                        if (null == fourthFragment) {
                            fourthFragment = FourthFragment.instance();
                        }
                        return fourthFragment;
                    default:
                        break;
                }
            }
            return null;
        }

        @Override
        public int getCount() {
            return VIEW_SIZE;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            if (position >= 0 && position < VIEW_SIZE) {
                switch (position) {
                    case VIEW_FIRST:
                        return "电纽";
                    case VIEW_SECOND:
                        return "发现";
                    case VIEW_THIRD:
                        return "消息";
                    case VIEW_FOURTH:
                        return "我";
                    default:
                        break;
                }
            }
            return null;
        }

        @SuppressWarnings("unchecked")
        @Override
        public Integer getPageIcon(int index) {
            if (index >= 0 && index < VIEW_SIZE) {
                switch (index) {
                    case VIEW_FIRST:
                        return R.drawable.home_main_icon_one_n;
                    case VIEW_SECOND:
                        return R.drawable.home_main_icon_two_n;
                    case VIEW_THIRD:
                        return R.drawable.home_main_icon_third_n;
                    case VIEW_FOURTH:
                        return R.drawable.home_main_icon_four_n;
                    default:
                        break;
                }
            }
            return 0;
        }

        @SuppressWarnings("unchecked")
        @Override
        public Integer getPageSelectIcon(int index) {
            if (index >= 0 && index < VIEW_SIZE) {
                switch (index) {
                    case VIEW_FIRST:
                        return R.drawable.home_main_icon_one_f;
                    case VIEW_SECOND:
                        return R.drawable.home_main_icon_two_f;
                    case VIEW_THIRD:
                        return R.drawable.home_main_icon_third_f;
                    case VIEW_FOURTH:
                        return R.drawable.home_main_icon_four_f;
                    default:
                        break;
                }
            }
            return 0;
        }

        @Override
        public Rect getPageIconBounds(int position) {
            return null;
        }
    }

    /**
     * 回调接口
     *
     * @author zhaoxin5
     */
    public interface MyTouchListener {
        public void onTouchEvent(MotionEvent event);
    }

    /*
     * 保存MyTouchListener接口的列表
     */
    private ArrayList<MyTouchListener> myTouchListeners = new ArrayList<MyTouchListener>();

    /**
     * 提供给Fragment通过getActivity()方法来注册自己的触摸事件的方法
     *
     * @param listener
     */
    public void registerMyTouchListener(MyTouchListener listener) {
        myTouchListeners.add(listener);
    }

    /**
     * 提供给Fragment通过getActivity()方法来取消注册自己的触摸事件的方法
     *
     * @param listener
     */
    public void unRegisterMyTouchListener(MyTouchListener listener) {
        myTouchListeners.remove(listener);
    }

    /**
     * 分发触摸事件给所有注册了MyTouchListener的接口
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        for (MyTouchListener listener : myTouchListeners) {
            listener.onTouchEvent(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);       //统计时长
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private void initConversationServiceAndListener() {
        mConversationUnreadChangeListener = new IYWConversationUnreadChangeListener() {

            @Override
            public void onUnreadChange() {
                // TODO Auto-generated method stub
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        showUnreadCounts();
                    }
                });
            }
        };
        if (null != mConversationService) {
            mConversationService.addTotalUnreadChangeListener(mConversationUnreadChangeListener);
        }else{
            Log.d("MainActivity","mConversationService is null");
        }

    }

    //设置连接状态的监听
    private void addConnectionListener() {
        mConnectionListener = new IYWConnectionListener() {
            @Override
            public void onDisconnect(int code, String info) {
                if (code == YWLoginCode.LOGON_FAIL_KICKOFF) {
                    //在其它终端登录，当前用户被踢下线
                    /*Toast.makeText(DnApplication.getContext(), getResources().getString(R.string.fail_kickoff), Toast.LENGTH_LONG).show();
                    YWLog.i("LoginSampleHelper", "被踢下线");
                    Intent intent = new Intent();
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setClass(MainActivity.this, LoginActivity.class);
                    MainActivity.this.startActivity(intent);*/
                }
            }

            @Override
            public void onReConnecting() {

            }

            @Override
            public void onReConnected() {

            }
        };
        if(null != mIkit){
            if(null != mIkit.getIMCore()){
                mIkit.getIMCore().addConnectionListener(mConnectionListener);
            }
        }
    }

    private void showUnreadCounts(){
        if (null != mConversationService) {
            int counts = mConversationService.getAllUnreadCount();
//            System.out.println("counts::::" + counts);
            // 设置桌面角标的未读数 部分手机不支持 隐藏掉
           /* try {
                if(null != mIkit){
                    mIkit.setShortcutBadger(counts);
                }
            }catch (Exception e){
                e.printStackTrace();
            }*/
            if (counts > 99) {
                mAPSTS.showDot(VIEW_THIRD, "99+");
            } else if (counts > 0) {
                mAPSTS.showDot(VIEW_THIRD, String.valueOf(counts));
            } else {
                mAPSTS.hideDot(2);
            }
        }else {
            Log.d("MainActivity","mConversationService is null");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(null != updateManager){
            updateManager.removeCheckListener();
        }
    }
}
